package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private WeChatProperties properties;
    @Resource
    private UserMapper userMapper;

    //微信登录
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 1.调用微信服务器接口，获得当前微信用户的 openId
        String openid = getOpenId(userLoginDTO.getCode());

        // 2.判断 openId 是否为空? 如果为空 则登录失败抛出异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);//登录失败
        }
        // 3.判断当前用户是否是新用户
        User user = userMapper.getByOpenId(openid);
        if(user == null){
            // 如果是新用户 则自动完成注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        // 返回用户对象
        return user;
    }

    //调用微信接口服务，返回微信用户id
    private String getOpenId(String code){
        // 1.调用微信服务器接口，获得当前微信用户的 openId
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",properties.getAppid());
        map.put("secret",properties.getSecret());
        map.put("js_code",code);
        map.put("grant_type", "authorization_code");
        // 返回的是一个 json字符串 数据
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        System.out.println("jsonObject的数据类型"+jsonObject.getClass());
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
